<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserPasswdService } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user.js'
const form = ref({
  password: '',
  newPassword: '',
  rePassword: ''
})
const validate1 = () => {
  // 自定义校验规则，新密码和旧密码不能一样
  const new_pwd = form.value.newPassword
  const old_pwd = form.value.password
  if (new_pwd === old_pwd) {
    return new Error('新密码不能和旧密码一样')
  }
}
const validate2 = () => {
  // 自定义校验规则，新密码和确认密码必须一样
  const new_pwd = form.value.newPassword
  const re_pwd = form.value.rePassword
  if (new_pwd !== re_pwd) {
    return new Error('新密码和确认密码必须一样')
  }
}
const rules = ref({
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validate1, trigger: 'blur' }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validate2, trigger: 'blur' }
  ]
})
const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
const onSubmit = async () => {
  const res = await useUserPasswdService(form.value)
  if (res.code === 1) {
    ElMessage.error(res.message)
    return
  }
  ElMessage.success('修改成功, 请重新登录')
  userStore.setUserInfo({})
  userStore.setToken('')
  router.replace('/login')
}
const onCancel = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <el-card style="max-width: 100%; min-height: 90%; margin: 20px" shadow="hover">
    <template #header>
      <div class="card-header">
        <strong>修改密码</strong>
      </div>
    </template>
    <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="用户密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" />
      </el-form-item>
      <el-form-item label="确认密码" prop="rePassword">
        <el-input v-model="form.rePassword" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="onCancel">重置</el-button>
    </template>
  </el-card>
</template>

<style scoped></style>
